package com.fitns.user.service.baseConfig;


import com.fitns.user.conf.ExcelConstants;
import com.fitns.user.constant.Constants;
import com.fitns.user.dao.baseConfig.TbCollectDataDao;
import com.fitns.user.dao.organ.OrganDao;
import com.fitns.user.dto.baseConfig.CollectDataCondition;
import com.fitns.user.dto.baseConfig.CollectDataList;
import com.fitns.user.dto.organ.OrganVO;
import com.fitns.user.exception.CollectDataMsgCode;
import com.fitns.user.exception.ServiceException;
import com.fitns.user.model.baseConfig.TbCollectData;
import com.fitns.user.utils.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiaoleilu.hutool.lang.Validator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *Created by schao on 2018/8/4
 *
 */

@Service
public class CollectDataService {

    @Resource
    private TbCollectDataDao tbCollectDataDao;
    @Resource
    private OrganDao organDao;


    public PageInfo<CollectDataList> search(CollectDataList tbCollectData) {
        if(StringUtils.isEmpty(tbCollectData)){
            return null;
        }

        PageHelper.startPage(tbCollectData.getPageNum(), tbCollectData.getPageSize());
        List<CollectDataList> tbCollectDataList=new ArrayList<>();
        String organName=tbCollectData.getOrganName();
        if(StringUtils.isEmpty(organName)) {
             tbCollectDataList = tbCollectDataDao.search(tbCollectData);
        }else{
             tbCollectDataList = tbCollectDataDao.searchByOrganName(tbCollectData);
        }
        for(CollectDataList data:tbCollectDataList){
            String str="";
            String[] organNames=data.getOrganName().split(",");
            int len=organNames.length;
            for (int i=len-1; i >= 0; i--){
                str+=organNames[i]+"-";
            }
            if(str!=""){
                str=str.substring(0,str.length()-1);
            }
            data.setOrganName(str);
        }
        PageInfo<CollectDataList> pageInfo = new PageInfo<>(tbCollectDataList);
        return pageInfo;
    }



    public TbCollectData findDetailed(CollectDataCondition tbCollectData) {
        if(StringUtils.isEmpty(tbCollectData)){
            return null;
        }
        if(StringUtils.isEmpty(tbCollectData.getId())){//根据经纬度查询
            if(!StringUtils.isEmpty(tbCollectData.getLgitude())&&
                    !StringUtils.isEmpty(tbCollectData.getLatitude())){
                List<TbCollectData> tbCollectDatalist= tbCollectDataDao.searchDetail(tbCollectData);
                if(StringUtils.isEmpty(tbCollectDatalist)){
                    return null;
                }
                return tbCollectDatalist.get(0);
            }
        }else {
            return tbCollectDataDao.select(tbCollectData.getId());
        }

        return null;
    }

    public TbCollectData insert(TbCollectData tbCollectData) {
        if(Validator.isNull(tbCollectData)){
            throw ServiceException.create(CollectDataMsgCode.Collect_ORGAN_OR_IS_NULL);
        }
        String nowDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        Timestamp insertDate=Timestamp.valueOf(nowDate);
        tbCollectData.setInputTime(insertDate);
        tbCollectData.setModifyTime(insertDate);
        tbCollectDataDao.inserts(tbCollectData);
        return tbCollectData;
    }

       public Long delete(Long id) {
        if(Validator.isNull(id)){
            throw ServiceException.create(CollectDataMsgCode.Collect_DATA_IS_NULL);
        }
        TbCollectData CollectData=tbCollectDataDao.select(id);
        if(Validator.isNull(CollectData)){
            throw ServiceException.create(CollectDataMsgCode.Collect_DATA_IS_NOT_EXIST);
        }
        tbCollectDataDao.delete(id);
        return id;
    }


    public TbCollectData modify(TbCollectData collectData) {
        if(Validator.isNull(collectData)){
           throw ServiceException.create(CollectDataMsgCode.Collect_DATA_IS_NULL);
        }
        TbCollectData tbCollectData=tbCollectDataDao.select(collectData.getId());
        if(Validator.isNull(tbCollectData)){
            throw ServiceException.create(CollectDataMsgCode.Collect_DATA_IS_NOT_EXIST);

        }
        collectData.setModifyTime(new Date());
        tbCollectDataDao.update(collectData);

        return tbCollectDataDao.select(collectData.getId());
    }



    @Transactional
    public void insertImage(TbCollectData collectData) {
//        TbCollectData tbCollectData = new TbCollectData();
//        BeanUtils.copyProperties(CollectData, tbCollectData);
        if (Validator.isNull(collectData.getId())) {
            collectData.setInputTime(new Date());
            this.insert(collectData);
        } else {
            collectData.setModifyTime(new Date());
            this.modify(collectData);
        }
    }
    public TbCollectData select(Long id) {
        return tbCollectDataDao.select(id);
    }



    public List<List<String>> export(CollectDataCondition CollectDataCondition){
        List<TbCollectData> CollectDataList=tbCollectDataDao.searchForExport(CollectDataCondition);
        List<List<String>> excelList = new ArrayList<>();
        for (int i = 0; i < CollectDataList.size(); i++) {
            if(i==0){
                excelList.add(this.getRowHeader(ExcelConstants.COLLECT_DATA_IMPORT_HEADER.class));
            }
            excelList.add(this.getrow(CollectDataList.get(i),i));
        }
        return excelList;
    }

    public List<String> getrow(TbCollectData CollectData, int i){
        List<String> row = new ArrayList<>();
        row.add(String.valueOf(i + 1));
        row.add(CollectData.getName());
        if(Validator.isNull(CollectData.getBeginTime())) {
            row.add("");
        }else {
            row.add(DateUtil.parseDateToStr(CollectData.getBeginTime(),Constants.DATESTR));
        }
        row.add(CollectData.getAddress());
        if(Validator.isNull(CollectData.getStatus())){
            row.add("");
        }else {
//            if (CollectData.getStatus() == 0) {
//                row.add("报废");
//            } else {
//                row.add("正常");
//            }
        }
        if(Validator.isNull(CollectData.getAcreage())){
            row.add("");
        }else {
            row.add(String.valueOf(CollectData.getAcreage()));
        }
        if(Validator.isNull(CollectData.getPopulation())){
            row.add("");
        }else {
            row.add(String.valueOf(CollectData.getPopulation()));
        }
        row.add(CollectData.getCounter());
        row.add(CollectData.getLiabler());
        row.add(CollectData.getPhone());
        row.add(CollectData.getTerminal());
        row.add(CollectData.getRfid());
        row.add((CollectData.getDescs()));
        row.add(CollectData.getLgitude());
        row.add(CollectData.getLatitude());
        return row;
    }

    public List<String> getRowHeader(Class clazz){
        Field[] fields=clazz.getDeclaredFields();
        List<String> rowHeader = new ArrayList<>();
        for(int i=0;i<fields.length-1;i++){
            try {
                Object object =fields[i].get(clazz);
                String value = object.toString();
                rowHeader.add(value);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return rowHeader;
    }
//
//    public List<CollectDataVo> importExcel(List<List<String>> excelList,String CollectType){
//
//        List<CollectDataVo> dtoList=new ArrayList<>();
//        List<CollectDataVo> msgList=new ArrayList<>();
//
//        for (int i = 1; i <excelList.size() ; i++) {
//            String number=excelList.get(i).get(0);
//            if(!StringUtils.isEmpty(number)){
//                CollectDataVo CollectDataVo=this.validateExcel(excelList.get(i),i);
//                if(!StringUtils.isEmpty(CollectDataVo.getMsg())){
//                    msgList.add(CollectDataVo);
//                }else {
//                    CollectDataVo dataVo=this.importDetail(excelList.get(i));
//                    dtoList.add(dataVo);
//                }
//            }
//        }
//        if(Validator.isEmpty(msgList)||msgList.size()==0){
//            if(Validator.isNotEmpty(dtoList)&&dtoList.size()!=0){
//              //  Map<String, Object> map = new HashMap<>();
//                dtoList.forEach(CollectDataVo -> {
//                    TbCollectData CollectData=new TbCollectData();
//                    BeanUtils.copyProperties(CollectDataVo,CollectData);
//                    CollectData.setCollectType(CollectType);
//                    tbCollectDataDao.inserts(CollectData);
//                });
//               /* map.put("list", dtoList);
//                tbCollectDataDao.insertImport(map);*/
//            }else {
//                CollectDataVo CollectDataVo=new CollectDataVo();
//                CollectDataVo.setMsg(ExcelConstants.FACLITY_DATA_IMPORT.EXCEL_IS_NULL);
//                msgList.add(CollectDataVo);
//            }
//        }
//
//        return msgList;
//
//    }
//
//    public CollectDataVo importDetail(List<String> excelList){
//        CollectDataVo CollectDataVo=new CollectDataVo();
//        CollectDataVo.setName(excelList.get(1));
//        if(Validator.isNotNull(excelList.get(2))) {
//            CollectDataVo.setBeginTime(DateUtil.parseStrToDate(excelList.get(13), Constants.DATESTR));
//        }
//        CollectDataVo.setAddress(excelList.get(3));
//        if(Validator.isNotNull(excelList.get(4))) {
//            CollectDataVo.setStatus(Integer.valueOf(excelList.get(4)));
//        }
//        if(Validator.isNotNull(excelList.get(5))) {
//            CollectDataVo.setAcreage(Float.valueOf(excelList.get(5)));
//        }
//        if(Validator.isNotNull(excelList.get(6))) {
//            CollectDataVo.setPopulation(Integer.valueOf(excelList.get(6)));
//        }
//        CollectDataVo.setCounter(excelList.get(7));
//        CollectDataVo.setLiabler(excelList.get(8));
//        CollectDataVo.setPhone(excelList.get(9));
//        CollectDataVo.setTerminal(excelList.get(10));
//        CollectDataVo.setRfid(excelList.get(11));
//        CollectDataVo.setDescs(excelList.get(12));
//        CollectDataVo.setLatitude(excelList.get(13));
//        CollectDataVo.setLgitude(excelList.get(14));
//        return CollectDataVo;
//    }
//
//    public CollectDataVo validateExcel(List<String> excelList, int i){
//        CollectDataVo CollectDataVo=new CollectDataVo();
//        StringBuilder msg = new StringBuilder();
//        if(StringUtils.isEmpty(excelList.get(1))){
//            msg.append("第"+(i+1)+"行"+ExcelConstants.FACLITY_DATA_IMPORT.Collect_DATA_NAME_IS_NULL);
//        }
//        if(StringUtils.isEmpty(excelList.get(2))){
//            msg.append("第"+(i+1)+"行"+ExcelConstants.FACLITY_DATA_IMPORT.Collect_DATA_START_DATE);
//        }
//        if(StringUtils.isEmpty(excelList.get(2))){
//            msg.append("第"+(i+1)+"行"+ExcelConstants.FACLITY_DATA_IMPORT.Collect_DATA_ADRESS);
//        }
//        if(StringUtils.isEmpty(excelList.get(2))){
//            msg.append("第"+(i+1)+"行"+ExcelConstants.FACLITY_DATA_IMPORT.Collect_DATA_STATUS);
//        }
//
//        if(!StringUtils.isEmpty(msg)){
//            CollectDataVo.setMsg(msg.toString());
//        }
//        return CollectDataVo;
//    }

}
